/**
 * article
 {
     _id:ObjectId,
     title:string,
     content:string,
     keys:[string],
     date:[timestamp]
     userId:ObjectId,
 }
 */
/**
 * comment
 {
     _id:ObjectId,
     articleId:ObjectId,
     userId:ObjectId,
     pId:ObjectId,
     content:string,
     date:[timestamp]
 }
 用户表的结构
 user{
    _id:ObjectId,
    username:string,
    nickname:string,
    password:string,
    email:string,
    date:date,
    state:int
}
 */
var mongoose = require('mongoose');
var Tool = require('./tool');
var Schema = mongoose.Schema;
var url = 'mongodb://localhost/test';
var Promise = require('bluebird');
mongoose.Promise = Promise;//设置promise
mongoose.connect(url);
var conn = mongoose.connection;

var article = new Schema({
    title:  String,
    content:   String,
    keys:{type:[String],set:formatKeys,get:getKeys},
    date: { type: Date, default: Date.now ,get:getDate},
    userId:Schema.Types.ObjectId
});
article.set('toObject', { getters: true });
var comment = new Schema({
    articleId:Schema.Types.ObjectId,
    userId:Schema.Types.ObjectId,
    pId:{type:Schema.Types.ObjectId,default:null},//父评论 都可以为null
    rootId:{type:Schema.Types.ObjectId,default:null},//根评论
    content:String,
    date:{type:Date,default:Date.now ,get:getDateSimple}
});
comment.set('toObject', { getters: true });
var user = new Schema({
    username:String,
    nickname:String,
    password:String,
    email:String,
    date: { type: Date, default: Date.now ,get:getDate},
    state:{type:Number,default:1}
});
user.set('toObject', { getters: true });
function formatKeys(keys){
    //console.log(keys);
    if(typeof keys === 'string'){
        console.log(keys.split(/,/));
        return keys.split(/,/);
    }else{
        return keys;
    }
}
function getKeys(keys){
    var str;
    if(Array.isArray(keys)){
        str = keys.reduce(function(p,c,i){
            if(i===0)
                return c;
            else
                return p+','+c;
        },'');
    }else{
        str = keys;
    }

    return str;
}

function getDate(date){
    return Tool.dateFormat(date,'{y}年{M}月{d}日 {h}点{m}分{s}秒');
}

function getDateSimple(date){
    return Tool.dateFormat(date,'{y}-{M}-{d} {h}:{m}:{s}',{align:1});
}
var Article = mongoose.model('article',article);
var Comment = mongoose.model('comment',comment);
var User = mongoose.model('user',user);
/**
 * loginMsg = {username:,password}
 * callback = function (retMsg){}
 * retMsg = {state:,message:,user:}
 * @param loginMsg
 * @param callback
 */
function login(loginMsg,callback){
    User.findOne({username:loginMsg.username,password:loginMsg.password},function(err,user){
        var retMsg = {};
        if(err){
            retMsg.state = 0;
            retMsg.message = '服务器错误';
        }else{
            if(user){
                retMsg.state = 1;
                retMsg.message = '登录成功';
                retMsg.user = user.toObject();
            }else{
                retMsg.state = 0;
                retMsg.message = '用户名或密码错误';
            }
        }
        if(callback){
            callback(retMsg);
        }
    })
}
/**
 * regMsg = {username:,nickname:,password:,email:}
 *
 * @param regMsg
 * @param callback
 */
function  register(regMsg,callback){
    var user = new User(regMsg);
    user.save(function(err,u){
        var regMsg = {};
        if(err){
            regMsg.state = 0;
            regMsg.message = '注册失败';
        }else{
            regMsg.state = 1;
            regMsg.message = '注册成功';
            regMsg.user = u.toObject();
        }
        if(callback){
            callback(regMsg);
        }
    })
}

/**
 * editMsg = {username:,nickname:,email:,}
 * @param id
 * @param editMsg
 * @param callback
 */
function editUser(id,editMsg,callback){
    User.count({_id:{$ne:id},$or:[{username:editMsg.username},{email:editMsg.email}]},function(err,count){
        var retMsg = {};
        if(err||count>0){//用户名或者邮箱是不能重复的(但是必须不能是当前id）
            retMsg.state = 0;
            retMsg.message = '更新出错或者用户名和邮箱已经存在';
            if(callback){
                callback(retMsg);
            }
        }else{
            User.findOneAndUpdate({_id:id},editMsg,{new:true},function(err,doc){
                if(err||!doc){
                    retMsg.state = 0;
                    retMsg.message = '更新出错或者没有找到该用户';
                }else{
                    retMsg.state = 1;
                    retMsg.message = '更新成功';
                    retMsg.user = doc.toObject();
                }
                if(callback){
                    callback(retMsg);
                }
            })
        }
    })
}
/**
 * editMsg ={password:}
 * @param id
 * @param editMsg
 * @param callback
 */
function editPassword(id,editMsg,callback){
    var retMsg = {};
    User.findOneAndUpdate({_id:id},editMsg,{new:true},function(err,doc){
        if(err||!doc){
            retMsg.state = 0;
            retMsg.message = '更新出错或者没有找到该用户';
        }else{
            retMsg.state = 1;
            retMsg.message = '更新成功';
            retMsg.user = doc.toObject();
        }
        if(callback){
            callback(retMsg);
        }
    })
}
/*************************文章部分**********************************/
/**
 * articleMsg = {title:,content:,userId:,keys:}
 * @param articleMsg
 * @param callback
 */
function addArticle(articleMsg,callback){
    var article = new Article(articleMsg);
    article.save(function(err,a){
        var regMsg = {};
        if(err){
            regMsg.state = 0;
            regMsg.message = '保存失败';
        }else{
            regMsg.state = 1;
            regMsg.message = '保存成功';
            regMsg.article = a.toObject();
        }
        if(callback){
            callback(regMsg);
        }
    })
}
/**
 * editMsg = {_id:,title:,content:,keys:}
 * @param editMsg
 * @param callback
 */
function editArticle(editMsg,callback){
    Article.findOneAndUpdate({_id:editMsg._id},editMsg,{new:true},function(err,a){
        var retMsg = {};
        if(err||!a){
            retMsg.state = 0;
            retMsg.message = '更新出错';
        }else{
            retMsg.state = 1;
            retMsg.message = '更新成功';
            retMsg.article = a.toObject();
        }
        if(callback){
            callback(retMsg);
        }
    })
}
/**
 *
 * @param id
 * @param callback
 */
function getArticle(id,callback){
    /*Article.findOne({_id:id},function(err,a){
     var retMsg = {};
     if(err||!a){
     retMsg.state = 0;
     retMsg.message ='系统出错或没有查到对应的文章';
     }else {
     retMsg.state = 1;
     retMsg.message = '查找成功';
     retMsg.article = a.toObject();
     /!**
     * 获取文章还要获取userId对应的用户信息
     *!/
     }
     if(callback){
     callback(retMsg);
     }
     })*/
    var p = Article.findOne({_id:id}).exec();
    var article;
    p.then(function(a){
        if(a){
            article = a;
            return User.findOne({_id: a.userId}).exec();
        }else{
            return Promise.reject('没有找到对应的文档');
        }
    }).then(function(u){
        var retMsg = {};
        retMsg.state = 1;
        retMsg.message = '查询成功';
        retMsg.article = article.toObject();
        retMsg.article.nickname = u.nickname;
        getComments(id,1,function(ret){
           if(ret.state){
               retMsg.comments = ret.comments;
           }else {
               retMsg.comments = [];
               console.log(ret.message);
           }
            if(callback){
                callback(retMsg);
            }
        });
        //if(callback){
        //    callback(retMsg);
        //}
    }).catch(function(msg){
        var retMsg = {};
        retMsg.state = 0;
        retMsg.message = '查询出错';
        console.log(msg);//输出出错信息
        if(callback){
            callback(retMsg);
        }
    })
}

/**
 *
 * @param id
 * @param callback
 */
function removeArticle(id,callback){
    /**
     * remove方法的回调函数function(err,msg)
     * 其msg会返回大量信息
     * 格式如下：
     * {
     *  result:{ok:1,n:1}
     *  connection:
     *      EventEmitter{
     *          domain:null,
     *          _events:
     *          {
     *              ...
     *          }
     *      }
     * }
     * ok:1不代表删除了数据，n代表删除数据条数
     *
     */
    Article.remove({_id:id},function(err){
        var retMsg = {};
        if(err){
            retMsg.state = 0;
            retMsg.message = '系统错误';
        }else {
            retMsg.state = 1;
            retMsg.message = '删除成功';
        }
        if(callback){
            callback(retMsg);
        }
    })
}
/**
 *
 * @param userId
 * @param page
 * @param callback
 */
function getArticlesByUser(userId,page,callback){
    if(!page){
        page = 1;
    }
    var pageSize = 10;
    /*Article.find({userId:userId}).skip((page-1)*pageSize).limit(pageSize).exec(
        function(err,articles){
        var retMsg = {};
        if(err){
            retMsg.state = 0;
            retMsg.message = '系统错误';
        }else {
            retMsg.state = 1;
            retMsg.message = '查询成功';
            retMsg.articles = articles.map(function(article){
                return article.toObject();
            });
            Article.find({userId:userId}).count(function(err,count){
                if(err){
                    retMsg.state = 0;
                    retMsg.message = '系统错误';
                }else {
                    retMsg.state = 1;
                    retMsg.message = '查询成功';
                    retMsg.pageNum = count/pageSize + 1;
                }
                if(callback){
                    callback(retMsg);
                }
            })
        }
        if(callback){//系统出错之后运行
            callback(retMsg);
        }
    });*/
    var p = Article.find({userId:userId}).skip((page-1)*pageSize).limit(pageSize).exec();
    p.then(function(arr){
        return Promise.all(arr.map(function(a){
            return Promise.all([a,User.findOne({_id: a.userId}).exec()]).then(function(msg){
                return msg;
            });
        })).then(function(msg){
            var retMsg = {};
            retMsg.state = 1;
            retMsg.message = '查询成功';
            retMsg.articles = [];
            msg.forEach(function(m){
                var a = m[0].toObject();
                a.nickname = m[1].nickname;
                retMsg.articles.push(a);
            });
            if(callback){
                callback(retMsg);
            }
        })
    }).catch(function(err){
        console.log(err);
        var retMsg = {};
        retMsg.state = 0;
        retMsg.message = '查询出错';
        if(callback){
            callback(retMsg);
        }
    })

}

/**
 *
 * @param page
 * @param callback
 */
function getArticles(page,callback){
    if(!page){
        page = 1;
    }
    var pageSize = 10;
    /*Article.find({}).skip((page-1)*pageSize).limit(pageSize).exec(
        function(err,articles){
            var retMsg = {};
            if(err){
                retMsg.state = 0;
                retMsg.message = '系统错误';
            }else {
                retMsg.state = 1;
                retMsg.message = '查询成功';
                retMsg.articles = articles.map(function(article){
                    return article.toObject();
                });
                Article.find({}).count(function(err,count){
                    if(err){
                        retMsg.state = 0;
                        retMsg.message = '系统错误';
                    }else {
                        retMsg.state = 1;
                        retMsg.message = '查询成功';
                        retMsg.pageNum = count/pageSize + 1;
                    }
                    if(callback){
                        callback(retMsg);
                    }
                })
            }
            if(callback){
                callback(retMsg);
            }
        });*/
    var p = Article.find({}).skip((page-1)*pageSize).limit(pageSize).exec();//与getArticlesByUser只有这一句不同
    p.then(function(arr){
        return Promise.all(arr.map(function(a){
            return Promise.all([a,User.findOne({_id: a.userId}).exec()]).then(function(msg){
                return msg;
            });
        })).then(function(msg){
            var retMsg = {};
            retMsg.state = 1;
            retMsg.message = '查询成功';
            retMsg.articles = [];
            msg.forEach(function(m){
                var a = m[0].toObject();
                a.nickname = m[1].nickname;
                retMsg.articles.push(a);
            });
            if(callback){
                callback(retMsg);
            }
        })
    }).catch(function(err){
        console.log(err);
        var retMsg = {};
        retMsg.state = 0;
        retMsg.message = '查询出错';
        if(callback){
            callback(retMsg);
        }
    })
}
/*************************评论部分**********************************/
//var comment = new Schema({
//    articleId:Schema.Types.ObjectId,
//    userId:Schema.Types.ObjectId,
//    pId:Schema.Types.ObjectId,
//    content:String,
//    date:{type:Date,default:Date.now ,get:getDate}
//});
/**
 * commentMsg = {articleid:,userId:,pId:,content:}
 * @param commentMsg
 * @param callback
 */
function addComment(commentMsg,callback){
    if(commentMsg.pId){
        var pComment = Cache.get(commentMsg.pId);
        if(pComment){
            if(pComment.rootId){
                commentMsg.rootId = pComment.rootId;
            }else{//pId本来就是根
                commentMsg.rootId = commentMsg.pId;
            }
        }else {
            Comment.findOne({_id:commentMsg.pId}).exec()
                .then(function(c){
                    if(c){
                        Cache.set(c.id,c);
                        if(c.rootId){
                            commentMsg.rootId = c.rootId;
                        }else{//pId本来就是根
                            commentMsg.rootId = commentMsg.pId;
                        }
                    }//如果没有查到pId 那么直接rootId为null(mongoose自动配置了)
                    save();
                });
            return;
        }
    }
    function save(){
        var comment = new Comment(commentMsg);
        comment.save(function(err,a){
            var regMsg = {};
            if(err){
                regMsg.state = 0;
                regMsg.message = '保存失败';
            }else{
                regMsg.state = 1;
                regMsg.message = '保存成功';
                regMsg.comment = a.toObject();
            }
            if(callback){
                callback(regMsg);
            }
        })
    }
    save();
}
/**
 * 评论删除的逻辑
 * 如果该评论没有子评论，那么直接删除
 * 如果该评论为根，则将其以他为父节点的子节点的pId设置为null以及rootId为null，并将其子节点的子孙节点的rootId设置为子节点
 * 如果该评论为中间部分则将其子节点的父节点设置其父节点
 * @param id
 * @param callback
 */
function removeComment(id,callback){
    /**
     * remove方法的回调函数function(err,msg)
     * 其msg会返回大量信息
     * 格式如下：
     * {
     *  result:{ok:1,n:1}
     *  connection:
     *      EventEmitter{
     *          domain:null,
     *          _events:
     *          {
     *              ...
     *          }
     *      }
     * }
     * ok:1不代表删除了数据，n代表删除数据条数
     *
     */
    //Comment.remove({_id:id},function(err){
    //    var retMsg = {};
    //    if(err){
    //        retMsg.state = 0;
    //        retMsg.message = '系统错误';
    //    }else {
    //        retMsg.state = 1;
    //        retMsg.message = '删除成功';
    //    }
    //    if(callback){
    //        callback(retMsg);
    //    }
    //})
    function removeCallback(err){
        var retMsg = {};
        if(err){
            retMsg.state = 0;
            retMsg.message = '系统错误';
        }else {
            retMsg.state = 1;
            retMsg.message = '删除成功';
        }
        if(callback){
            callback(retMsg);
        }
    }
    //抽楼怎么处理
    /**
     * 处理的难点就是当当前节点为root时如何修改子孙节点的root
     */
    //var comment = Cache.get(id);
    //if(comment){
    //    if(comment.pId){
    //
    //    }
    //}else{
    //
    //}
    Comment.findOne({_id:id}).exec().then(function(c){
        if(c){
            Promise.all([Comment.findOne({_id: c.pId}).exec(),//查找父节点
                Comment.find({pId: c._id}).exec(),//查找子节点
                Comment.find({rootId: c._id}).exec()//查找以它为根的节点
            ]).then(function(result){
                var parent = result[0];
                var children = result[1];
                var subRoot = result[2];
                if(!c.pId){//c是根节点
                    if(children.length === 0){//根节点 但是没有子节点 直接删除
                        c.remove({_id:id},removeCallback);
                    }else{
                        /**
                         * 1.将所有节点都放入cacheTree中，包括根节点
                         *
                         */
                        var cacheTree = {};
                        cacheTree[c.id] = {node:c,children:[]};
                        subRoot.forEach(function(r){
                          cacheTree[r.id] = {node:r,children:[]};
                        });
                        /**
                         * 2.遍历cacheTree，给每个节点添加子节点
                         */
                        cacheTree.forEach(function(n){
                            if(n.node.pId){
                                cacheTree[n.node.pId].children.push(n.node);
                            }
                        });
                        /**
                         * 3.清除根节点的直接子节点的rootId和parentId
                         */
                        cacheTree[c.id].children.forEach(function(child){
                            child.rootId = null;
                            child.parentId =null;
                            cacheTree[child.id].repair = true;//设置已修改标识符
                        });
                        function repairRoot(rootId,sub){//修正子节点
                            var arr = cacheTree[sub.id].children;
                            arr.forEach(function(child){
                                child.rootId = rootId;
                                cacheTree[child.id].repair = true;
                                repairRoot(rootId,child);
                            })
                        }

                        /**
                         * 4.对子节点的后代节点设置新的rootId
                         */
                        cacheTree[c.id].children.forEach(function(child){
                            repairRoot(child._id,child);
                        });
                        /**
                         * 5.保存修改数据
                         */
                        Object.keys(cacheTree).forEach(function(n){//保存修改
                            if(n.node.repair){
                                n.node.save();
                            }
                        })
                        /**
                         * 6.删除节点
                         */
                        c.remove({_id:id},removeCallback);
                    }
                }else{
                    if(children.length === 0){//不是根节点但是没有子节点直接删除
                        c.remove({_id:id},removeCallback);
                    }else {
                        children.forEach(function(child){
                            child.pId = parent._id;
                            child.save();
                        });
                        c.remove({_id:id},removeCallback);
                    }
                }
            })
        }
    })
}
/**
 *
 * 评论的查找功能就是要查找某个文章对应的评论，评论有父评论
 * 评论的查询工作相对复杂
 * （1）查找父评论为空的评论
 * （2）查找以上面评论为根节点的评论（要增加一个rootId字段）
 * 评论的显示如下：
 * 东哥：五星好评
 *  -宙斯回复东哥：赞同
 *  -百年孤独回复东哥：赞同
 *  -独孤求败回复百年孤独：赞同
 *
 *  从上面的的实例中可以看出要进行多次数据库查找
 *  其中用户信息需要多次读取，显然这里需要优化
 *
 *  评论是带在文章页面下面的，也可以单独显示
 *  在页面中控制显示多少
 *  在单独页面中显示多少
 *  如何显示更多评论
 *
 *  如何设计一个cache
 *  cache什么内容？
 *  用户、评论、文章以及页面
 *  方法:
 *  get获取cache
 *  put保存cache
 */
function cacheManager(){
    var cache = {};
    function set(key,val){
        cache[key] = val;
    }
    function get(key){
        return cache[key];
    }
    function del(key){
        try{
            delete cache[key];
        }catch (err){
            throw err;
        }
    }
    function count(){
        return Object.keys(cache).length;
    }
    return {get:get,set:set,del:del,count:count}
}

var Cache = cacheManager();
/**
 *
 * @param articleId
 * @param page
 * @param callback
 */
function getComments(articleId,page,callback){
    if(!page){
        page = 1;
    }
    var pageSize = 10;
    /**
     * 1.找出10条最新的评论
     */
    var p = Comment.find({articleId:articleId})
        .skip((page-1)*pageSize)
        .limit(pageSize)
        .sort({date:'desc'})//对日期进行降序排列
        .exec();
    /**
     * 2.分别以这些评论的根评论节点为条件查找所有以该根评论为根评论的评论。
     */
    p.then(function(arr){
        //return Promise.all(arr.map(function(a){
        //    return Promise.all([a,User.findOne({_id: a.userId}).exec()]).then(function(msg){
        //        return msg;
        //    });
        //})).then(function(msg){
        //    var retMsg = {};
        //    retMsg.state = 1;
        //    retMsg.message = '查询成功';
        //    retMsg.comments = [];
        //    msg.forEach(function(m){
        //        var a = m[0].toObject();
        //        a.nickname = m[1].nickname;
        //        retMsg.comments.push(a);
        //    });
        //    if(callback){
        //        callback(retMsg);
        //    }
        //})
        return Promise.all(arr.map(function(c){
            if(c.rootId){
                return Promise.all([c,Comment.find({$or:[{_id: c.rootId},{rootId: c.rootId}]}).exec()])
                    /**
                     * {$or:[{_id: c.rootId},{rootId: c.rootId}]}查找根节点或者以该节点为根节点的评论
                     */
                    .then(function(ret){
                        return ret;//[comment,[comment...]]
                    })
            }else {//如果当前评论就是根评论是不需要继续查询的
                return [c,[]];
            }

        })).then(function(result){
            var lastComments = [];
            for(var i=0;i<result.length;i++){
                var ret = result[i];
                lastComments.push(ret[0]);
                Cache.set(ret[0].id,ret[0]);
                var comments = ret[1];
                for(var j=0;j<comments.length;j++){
                    var comment = comments[j];
                    Cache.set(comment.id,comment);
                }
            }
            var retComments = [];
            lastComments.forEach(function(comment){
                var comments = [];
                //comments.push(comment);
                while(1){
                    if(comment.pId){//有父评论节点才能继续循环
                        comments.push(comment);
                        comment = Cache.get(comment.pId);
                    }else {
                        comments.push(comment);
                        retComments.push(comments);
                        break;
                    }
                }
            });

            /**
             * 查找用户信息
             *
             */
            Promise.all(retComments.map(function(comments){
                return Promise.all(comments.map(function(comment){
                    return User.findOne({_id:comment.userId}).exec().then(function(u){
                        //return comment
                        comment = comment.toObject();
                        comment.nickname = u.nickname;
                        return comment;
                    });
                }))
                //    .then(function(result){
                //    console.log(result);
                //})
                    ;
            })).then(function(result){
                //console.log(result);
                var retMsg = {};
                retMsg.state = 1;
                retMsg.message ='查询成功';
                retMsg.comments = result;
                if(callback){//还需要查找用户信息
                    callback(retMsg);
                }
            });
            //var retMsg = {};
            //retMsg.state = 1;
            //retMsg.message ='查询成功';
            //retMsg.comments = retComments;
            //if(callback){//还需要查找用户信息
            //    callback(retMsg);
            //}
        })
    }).catch(function(err){
        console.log(err);
        var retMsg = {};
        retMsg.state = 0;
        retMsg.message = '查询出错';
        if(callback){
            callback(retMsg);
        }
    })
}


/**************************输出******************************/
module.exports = {
        login: login,
        register:register,
        editUser:editUser,
        editPassword:editPassword,
        addArticle:addArticle,
        editArticle:editArticle,
        removeArticle:removeArticle,
        getArticle:getArticle,
        getArticles:getArticles,
        getArticlesByUser:getArticlesByUser,
        getComments:getComments,
        addComment:addComment,
        removeComment:removeComment
    };
+function(){
    //login({username:'dongge',password:'123456'},console.log);//测试成功
    //var u = new User({username:'dongge',nickname:'xxx',password:'123456',email:'442704997@qq.com'});
    //register({username:'dongge',nickname:'xxx',password:'123456',email:'442704997@qq.com'},console.log);
    //editPassword('569528daa47d315817a2b5db',{password:'987654321'},console.log);
    //editUser('569528daa47d315817a2b5db',{username:'admin',nickname:'zeus',email:'442704997@qq.com'},console.log);
}();
+function(){
    //建立用户
    //var u = new User({username:'dongge',nickname:'xx',password:'123456',email:'yuzhou346694246@126.com',state:1});
    //u.save(function(err){
    //    console.log(u.id);
    // });
    //查找用户56a716ef692038cc11163a00
    //User.find({_id:{$ne:'56952c906ce0a2e00a59b3c9'},username:'admin'},function(err,doc){
    //    console.log(doc);
    //})
    //User.findOne({username:'root'},function(err,u){
    //User.find({username:'root'},function(err,u){
    //    console.log(u);
    //})
    //User.findOneAndUpdate({_id:'568ff3c5dba46b0412251fe'},{username:'dongge'},{new:true},function(err,doc){
    //    console.log(doc);
    //})
    //删除用户
    //User.remove({username:'admin'},function(err,a){
    //    console.log(a);
    //    console.log(err);
    //})
    //编辑用户
    //User.update({_id:'569528daa47d315817a2b5db'},{$set:{username:'root',nickname:'xx00'}},function(err,doc){
    //    console.log(doc);
    //    console.log(err);
    //});
    //登录
    //User.findOne({username:'root',password:'123456'},function(err,u){
    //    console.log(u);
    //})
}();

+function(){
    //新建文章
    //var a = new Article({title:'dongge',content:'this is a test',keys:['xxx','jquery'],userId:'56a716ef692038cc11163a00'});
    //a.save(function(err,d){
    //    console.log(d);
    //    //console.log(a);
    //})
    //查找文章568ff9879d79a91424171734
    //Article.findById('568ff9879d79a91424171734').then(function(a){
    //    //if(a.userId)
    //    console.log(a);
    //    console.log(a.keys);
    //    return User.findById(a.userId);
    //
    //}).then(function(u){
    //    console.log(u);
    //}();
    //修改
    //var articleMsg = {_id:'568ff9879d79a91424171734',title:'我不是东哥',content:'这个杀手不太冷',keys:"jquery,dongge"};
    //Article.update({_id:articleMsg._id},articleMsg, function (err,msg) {
    //    if(err) throw err;
    //    console.log(msg);
    //});
    //Article.update({_id:'568ff9879d79a91424171734'},{$set:{userId:'568ff3c5dba46b041225cffe'}},function(err,n){
    //    console.log(err);
    //    console.log(n);
    //})
    //Article.find({},function(err,arr){
    //    console.log(arr);
    //})
    //var articleMsg = {_id:'568ff9879d79a91424171734',title:'我不是东哥啊',content:'这个杀手不太冷',keys:"jquery,dongge"};
    ////editArticle(articleMsg,console.log);
    //Article.findOneAndUpdate({_id:articleMsg._id},articleMsg, function (err,msg) {
    //    if(err) throw err;
    //    console.log(msg);
    //});
    //getArticles(1,console.log);
    //getArticlesByUser('569528daa47d315817a2b5db',1,console.log);
    //getArticlesByUser('1',1,console.log);
    //Article.find({userId:'569528daa47d315817a2b5db'},function(err,docs){
    //    console.log(docs);
    //})
}();

+function(){//评论
    //var c = new Comment({articleId:'568fb5d2dc1103ac2202d72e',userId:'568ff3c5dba46b041225cffe',content:'这是一条评论'});
    //c.save(function(err,c){
    //    console.log(c);
    //});
    //getComments('568fb5d2dc1103ac2202d72e',1,console.log);
    Comment.findOne({_id:null}).exec().then(function(c){
        console.log(c);
    })
}();
/*+function(){
 Article.findById('568fbfaf0cbcae5c18bca741',function(err,doc){
 console.log(doc);
 })
 }();*/
